package de.fhffm.scs.simulator.regulator;

import java.util.List;

import de.fhffm.scs.simulator.data.BloodSugarLevel;

public class BloodSugarLevelEstimator implements BloodSugarEstimator {

	
	BloodSugarLevel estimatedBloodvalue;
	int numberofponits;
	long futureTimestamp = 0;
	int Sumtimestamp = 0;
	long slope;
	int modelBloodsugar;
	int Sumbloodsugarlevels;

	long Sumtimestampssqure = 0;

	int Sumofproducttimestampandbloodsugarlevel = 0;

	// using the gradient to estimate future value Y=slope*+model

	public BloodSugarLevel getEstimatedFutureBloodSugarLevel(
			List<BloodSugarLevel> pastBloodSugarLevels, long futureTimestamp) {
		calculateslope(pastBloodSugarLevels);
		int newbloodsugarlevel = (int) (slope * futureTimestamp + modelBloodsugar);
		estimatedBloodvalue = new BloodSugarLevel(newbloodsugarlevel,
				futureTimestamp);
		return estimatedBloodvalue;
	}

	private void performcalculationonpoints(List<BloodSugarLevel> pastBloodSugarLevels) {
		// loop through the ponits
		BloodSugarLevel thisbloodsugarlevel;
		int bloodsugar;
		long timestamp;
		for (numberofponits = 0; numberofponits < pastBloodSugarLevels.size(); numberofponits++) {
			thisbloodsugarlevel = pastBloodSugarLevels.get(numberofponits);
			bloodsugar = thisbloodsugarlevel.getLevel();
			timestamp = thisbloodsugarlevel.getTimestamp();
			Sumtimestamp += timestamp;
			Sumbloodsugarlevels += bloodsugar;
			Sumtimestampssqure += timestamp * timestamp;
			Sumofproducttimestampandbloodsugarlevel += timestamp
					* (long) bloodsugar;

		}

	}

	// calculate the gradeint of the line
	private void calculateslope(List<BloodSugarLevel> pastBloodSugarLevels) {
		performcalculationonpoints(pastBloodSugarLevels);
		int meanofBloodsugarvalues = Sumbloodsugarlevels / numberofponits;
		long meantimestampvalues = Sumtimestamp / numberofponits;

		slope = (Sumofproducttimestampandbloodsugarlevel - Sumtimestamp
				* meanofBloodsugarvalues)
				/ (Sumtimestampssqure - Sumtimestamp * meantimestampvalues);

		modelBloodsugar = (int) (meanofBloodsugarvalues - slope
				* meantimestampvalues);

	}
}
